<?php


namespace app\controller;


use think\facade\Db;
//用于1.短信验证码发送2.验证码验证
class ShortMessage
{

    protected $userName = 'xxxx';
    protected $password = 'xxxx';//登录密码：lucky123
    protected $redis_key = 'xxxx.yyuebd.com-send_code-';
    protected $redis_time = 300;//redis有效时间，即短信有效时间(秒)
    protected $interval_time = 120;//提示间隔时间后再发送(秒)
    public $redis;
    public function __construct(){
        $this->redis = new \think\cache\driver\Redis();
    }
    //一般用在前端 短信验证码按钮 触发
    public function send_message_f($message_code,$content){
        /**
        --
        -- 表的结构 `send`
        --

        CREATE TABLE `send` (
        `send_id` int(11) NOT NULL,
        `send_phone` char(11) NOT NULL,
        `send_num` int(11) NOT NULL DEFAULT '0',
        `send_message_time` bigint(20) NOT NULL,
        `send_time` date NOT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

        --
        -- 转储表的索引
        --

        --
        -- 表的索引 `send`
        --
        ALTER TABLE `send`
        ADD PRIMARY KEY (`send_id`);

        --
        -- 在导出的表使用AUTO_INCREMENT
        --

        --
        -- 使用表AUTO_INCREMENT `send`
        --
        ALTER TABLE `send`
        MODIFY `send_id` int(11) NOT NULL AUTO_INCREMENT;
        COMMIT;

         **/

        //禁止get请求
        if(request()->isGet()){
            return json(['status'=>500,'msg'=>'非法请求']);
        }
        $submit_phone = request()->param('submit_phone');
        if(!preg_match('/^1[3456789]\d{9}$/',$submit_phone)){
            return json(['status'=>500,'msg'=>'请输入正确的手机号码']);
        }

        $message_num =  json_decode(getMessageSum($this->userName,$this->password),true);
        if($message_num['balance']<=0 || $message_num['balance'] - 3 <= 0){
            return json(['status'=>500,'msg'=>'短信余额不足']);
        }
//        $where = [['send_phone','=',$submit_phone],['send_time','=',date("Y-m-d")]];
        //查询当前号码当天是否发送过验证码
        $send = Db::table('send')
            ->where('send_phone',$submit_phone)
            ->where('send_time',date("Y-m-d"))
            ->find();
        if(empty($send)){//没有发送过验证码，则
            $insert_result = [
                'send_phone'=>$submit_phone,
                'send_num'=>1,
                'send_message_time'=>time(),
                'send_time'=>date('Y-m-d')
            ];
            //新增一条记录
            $send_id =  Db::table('send')->insertGetId($insert_result);
        }else{//如果当天已发送
            //且数量超过或等于10条，则禁止发送
            if($send['send_num']>=10){
                return json(['status'=>500,'msg'=>'您今天提交过多，明天后再提交']);
            }
            //如果还在$this->interval_time秒内，则不可重新发送
            if(time()-$send['send_message_time']<$this->interval_time){
                $sy_time = $this->interval_time - (time()-$send['send_message_time']);
                return json(['status'=>500,'msg'=>"发送频繁，请{$sy_time}秒后再试"]);
            }
            //否则，次数加 + 1
            Db::table('send')
                ->where('send_phone',$submit_phone)
                ->where('send_time',date("Y-m-d"))
                ->update([
                    'send_message_time'=>time(),
                    'send_num'=>Db::raw('send_num+1'),
                ]);
        }
        $key = $this->redis_key.$submit_phone;
        $this->redis->set($key,$message_code,$this->redis_time);
        $send_dx =  json_decode(shortMessage($this->userName,$this->password,$submit_phone,$content),true);
        if($send_dx['code']==0){
            return ['status'=>200,'msg'=>'短信发送成功'];
        }else{
            return ['status'=>500,'msg'=>'短信发送失败'];
        }

    }
    public function checkCode($submit_phone,$code){
        $key = $this->redis_key.$submit_phone;
        $redisVal = $this->redis->get($key);
        if($redisVal == $code) return true;else return false;
    }
    //后台批量发送【根据需求改动】
    /**
        后台按钮【批量发送】
        <el-button  size="small" type="primary" @click="sendMailMessage('','all')">
        批量发送短信
        </el-button>
        后台按钮【单人发送】
        <el-button v-if="row.is_send_message !=1 " size="mini" type="primary" @click="sendMailMessage(row.submit_id,'one')">
        发送短信
        </el-button>
        js方法：
    sendMailMessage(submit_id,type){
        this.$confirm('此操作将会发送短信, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        }).then(() => {
            sendMailMessage({submit_id:submit_id,type:type}).then((res)=>{
                this.$alert(res.msg, '发送状态', {
                confirmButtonText: '确定',
                callback: action => {
                this.fetchData()
                }
                });
            })
        }).catch(() => {
        this.$message({
        type: 'info',
        message: '取消'
        });
        });
        mysql:字段
        is_send_message：默认 0 ，成功 1 ，失败 2
    },
    **/
    public function sendHtMessage(){
        $userName = "test126";
        $pssword = "VbCWV2bA4Sol";
        $table = "submit";
        $field0 = "submit_id";
        $field1 = "submit_phone";
        $field2 = "submit_code";
        $where = [
            ['is_send','=',0]
        ];
        $limit = 1000;//每次发的量,最多1000条
        $user_data_num = Db::table($table)->where($where)->count();
        if(empty($user_data_num)){return json(['status'=>500,'msg'=>'当前没有人需要发短信']);}
        $update_send = ['is_send'=>1];
        if($user_data_num > $limit){//计算有几页
            $sum = $user_data_num / $limit;
            //整数部分
            $integerPart = floor($sum);
            //小数部分
            $decimalPart  =$sum - $integerPart;
            if($decimalPart>0){
                $page =  $integerPart + 1;
            }else{
                $page = $integerPart;
            }
            $success_num = 0;
            $fail_num = 0;
            for($i = 1;$i<=$page; $i ++){
                $messageList = Db::table($table)
                    ->page($i,$limit)
                    ->filter(function($data) use ($field0,$field1,$field2){
                        $result = [];
                        $result['phone'] = $data[$field1];//必须
                        $result['callData'] = $data[$field0];//回传值
                        $result['content'] = "【望东科技】您的用户标识为{$data[$field2]}，请勿泄露给他人。";//必须
                        return $result;
                    })->select()->toArray();
                $idArr = Db::table($table)->page($i,$limit)->column($field0);
                $sendData = json_decode(shortMessage($userName,$pssword,$messageList),true);
                if($sendData['code'] == 0 && $sendData['smsCount'] == count($messageList)){
                    Db::table($table)->where($field0,'in',$idArr)->update($update_send);
                    $success_num =  $success_num + $sendData['smsCount'];
                }else{
                    $sendData['status'] = 500;
                    $fail_num = $fail_num + count($messageList);
                }
            }

        }else{//直接发送短信
            $messageList = Db::table($table)
                ->where($where)
                ->filter(function($data) use ($field0,$field1,$field2){
                    $result = [];
                    $result['phone'] = $data[$field1];//必须
                    $result['callData'] = $data[$field0];//回传值
                    $result['content'] = "【望东科技】您的用户标识为{$data[$field2]}，请勿泄露给他人。";//必须
                    return $result;
                })->select()->toArray();
            $sendData = json_decode(shortMessage($userName,$pssword,$messageList),true);
            if($sendData['code'] == 0 && $sendData['smsCount'] == count($messageList)){
                $success_num = $sendData['smsCount'];
                $sendData['count'] = $sendData['smsCount'];
                Db::table($table)->where($where)->where($field0,'>',0)->update($update_send);
            }else{$fail_num = count($messageList);}
        }
//   "code" => 0
//   "message" => "处理成功"
//   "data" => array:1 [▼
//     0 => array:5 [▼
//       "code" => 0
//       "message" => "处理成功"
//       "msgId" => 279500612
//       "phone" => "18084506170"
//       "smsCount" => 1
//     ]
//   ]
//   "smsCount" => 1
//   "status" => 200
//   "count" => 1
        return json(['status'=>200,'msg'=>"成功条数：".$success_num."，失败条数：".$fail_num]);
    }
}